'use strict';

const Service = require('egg').Service;

class AddressService extends Service {

  // 新增
  async createAddress(payload) {
    const { app } = this;
    // 插入数据
    const res = await app.model.MallAddress.create(payload);
    return res.dataValues;
  }

  // 获取列表
  async getAddress(user_id) {
    const { app } = this;
    try {
      return await app.model.MallAddress.findAll({
        attributes: [ 'id', 'consignee', 'phone', 'address', 'is_default' ],
        order: [[ 'createdAt', 'desc' ]],
        where: { user_id },
      });
    } catch (error) {
      console.error(error);
      return null;
    }
  }

  // 删除
  async delAddress(id) {
    const { app } = this;
    return await app.model.MallAddress.destroy({ where: { id } });

  }

  // 修改
  async updateAddress(id, address) {
    const { app } = this;
    const res = await app.model.MallAddress.update(address, { where: { id } });
    return res[0] > 0;
  }

  // 修改
  async setDefault(user_id, id) {
    const { app } = this;
    await app.model.MallAddress.update({ is_default: false }, { where: { user_id } });
    return await app.model.MallAddress.update({ is_default: true }, { where: { id } });

  }
}

module.exports = AddressService;
